package com.LachesismStorm.lachesism.member.util;

import lombok.SneakyThrows;
import org.checkerframework.checker.units.qual.C;

import javax.imageio.ImageIO;
import javax.net.ssl.HttpsURLConnection;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;

/**
 * @Author lachesism
 * @Date 2024-12-31 18:42
 **/
public class certUtil {

    // Step 1: 获取 PHPSESSID Cookie
    @SneakyThrows
    public static String getCertCookie() {
        String urlString = "https://www.hrjnjd.com/zscx.html";
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");

        // 设置请求头
        connection.setRequestProperty("Accept", "image/webp,image/avif,image/jxl,image/heic,image/heic-sequence,video/*;q=0.8,image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5");
        connection.setRequestProperty("Accept-Encoding", "gzip, deflate, br");
        connection.setRequestProperty("Accept-Language", "zh-CN,zh-Hans;q=0.9");
        connection.setRequestProperty("Referer", "https://www.hrjnjd.com/zscx.html");
        connection.setRequestProperty("Priority", "u=5, i");
        connection.setRequestProperty("Sec-Fetch-Dest", "image");
        connection.setRequestProperty("Sec-Fetch-Mode", "no-cors");
        connection.setRequestProperty("Sec-Fetch-Site", "same-origin");
        connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");

        // 获取响应头中的 cookies
        Map<String, List<String>> headers = connection.getHeaderFields();
        List<String> cookies = headers.get("Set-Cookie");

        // 提取 PHPSESSID cookie
        for (String cookie : cookies) {
            if (cookie.contains("PHPSESSID")) {
                return cookie.split(";")[0].split("=")[1]; // 提取 PHPSESSID 值
            }
        }
        return null;
    }

    // Step 2: 使用获取的 Cookie 请求验证码图片
    @SneakyThrows
    public static String getCaptchaImage(String cookie) {
        String urlString = "https://www.hrjnjd.com/channel/memberCode/";
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");

        // 设置请求头，带上获取到的 Cookie
        connection.setRequestProperty("Accept", "image/webp,image/avif,image/jxl,image/heic,image/heic-sequence,video/*;q=0.8,image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5");
        connection.setRequestProperty("Accept-Encoding", "gzip, deflate, br");
        connection.setRequestProperty("Accept-Language", "zh-CN,zh-Hans;q=0.9");
        connection.setRequestProperty("Referer", "https://www.hrjnjd.com/zscx.html");
        connection.setRequestProperty("Priority", "u=5, i");
        connection.setRequestProperty("Sec-Fetch-Dest", "image");
        connection.setRequestProperty("Sec-Fetch-Mode", "no-cors");
        connection.setRequestProperty("Sec-Fetch-Site", "same-origin");
        connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");
        connection.setRequestProperty("Cookie", "PHPSESSID=" + cookie);
        // 获取验证码图片
        InputStream inputStream = connection.getInputStream();
        BufferedImage captchaImage = ImageIO.read(inputStream); // 将输入流转换为图片
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(captchaImage, "PNG", baos);
        byte[] imageBytes = baos.toByteArray();
        return Base64.getEncoder().encodeToString(imageBytes);
    }

    // 创建一个 static 方法来模拟请求
    @SneakyThrows
    public static String queryCertificate(String name, String certificateNumber, String idCardNumber, String captcha, String cookie) throws IOException {
        // 获取当前时间戳
        String timestamp = String.valueOf(System.currentTimeMillis());
        // 请求的 URL，包含时间戳
        String urlString = "https://www.hrjnjd.com/index.php/api/SearchCertificate?random=" + timestamp;

        // 创建 URL 对象
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        // 设置请求方法为 POST
        connection.setRequestMethod("POST");

        // 设置请求头
        connection.setRequestProperty("Accept", "application/json, text/javascript, */*; q=0.01");
        connection.setRequestProperty("Accept-Encoding", "gzip, deflate, br");
        connection.setRequestProperty("Accept-Language", "zh-CN,zh-Hans;q=0.9");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Cookie", "PHPSESSID=" + cookie);
        connection.setRequestProperty("Origin", "https://www.hrjnjd.com");
        connection.setRequestProperty("Referer", "https://www.hrjnjd.com/zscx.html");
        connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");
        connection.setRequestProperty("X-Requested-With", "XMLHttpRequest");

        // 准备 POST 请求体参数
        String postData = "InfoTitle=" + URLEncoder.encode(name, "UTF-8") +
                "&InfoSContent=" + URLEncoder.encode(certificateNumber, "UTF-8") +
                "&F3=" + URLEncoder.encode(idCardNumber, "UTF-8") +
                "&Code=" + URLEncoder.encode(captcha, "UTF-8") +
                "&button=" + URLEncoder.encode("证书查询", "UTF-8") +
                "&__hash__=" + URLEncoder.encode("523e4516ddb2a750106f182c4b9b363b_77e6bc4ded5e317239f2191c20e3d4c6", "UTF-8");

        // 向连接写入数据
        connection.setDoOutput(true);
        try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) {
            outputStream.writeBytes(postData);
            outputStream.flush();
        }

        // 获取响应码
        int responseCode = connection.getResponseCode();
        if (responseCode == 200) {
            // 解压 GZIP 响应内容
            InputStream inputStream = connection.getInputStream();
            if ("gzip".equals(connection.getContentEncoding())) {
                inputStream = new GZIPInputStream(inputStream);
            }

            // 读取响应数据
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }

            reader.close();
            return response.toString();  // 返回响应内容
        } else {
            return "请求失败，响应码：" + responseCode;
        }
    }
    // 根据返回的 Data 获取新的 URL 并发起 GET 请求
    public static String fetchCertificateInfo(String data,String cookie) throws IOException {
        // 拼接完整 URL
        String urlString = "https://www.hrjnjd.com" + data;
        System.out.println("urlString:   "+urlString);

        // 创建 URL 对象
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        // 设置请求方法为 GET
        connection.setRequestMethod("GET");

        // 设置请求头
        connection.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
        connection.setRequestProperty("Accept-Encoding", "gzip, deflate, br");
        connection.setRequestProperty("Accept-Language", "zh-CN,zh-Hans;q=0.9");
        connection.setRequestProperty("Cookie", "PHPSESSID=rpbjb9qhq3q3th44cgsaln0t1n");
        connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");
        connection.setRequestProperty("Cookie", "PHPSESSID=" + cookie);

        // 获取响应码
        int responseCode = connection.getResponseCode();
        if (responseCode == 200) {
            // 解压 GZIP 响应内容
            InputStream inputStream = connection.getInputStream();
            if ("gzip".equals(connection.getContentEncoding())) {
                inputStream = new GZIPInputStream(inputStream);
            }

            // 读取响应数据
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();
            return response.toString();  // 返回页面内容（例如证书详情）
        } else {
            return "请求失败，响应码：" + responseCode;
        }
    }
    // 提取 Data 字段的值
    public static String extractDataFromJson(String jsonResponse) {
        // 正则表达式匹配 Data 字段
        Pattern pattern = Pattern.compile("\"Data\":\"(.*?)\"");
        Matcher matcher = pattern.matcher(jsonResponse);
        if (matcher.find()) {
            return matcher.group(1).replace("\\","");  // 返回匹配的 Data 值
        } else {
            return null;  // 没有找到 Data 字段
        }
    }

    // 提取匹配的值，并返回提取的字段内容
    public static String extractValue(String html, String regex) {
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(html);
        if (matcher.find()) {
            return matcher.group(1);  // 返回第一个捕获组的内容
        }
        return "未找到";  // 如果没有找到匹配项，返回“未找到”
    }
    @SneakyThrows
    public static String formatContent(String data,String cookie){
        String finalResult = fetchCertificateInfo(data,cookie);
//        String replaceInfo1 = "<div class=\"html\">\t\t<div class=\"top\">\t\t\t<div class=\"logo\">\t\t\t\t<a href=\"/\">\t\t\t\t\t<img src=\"/Upload/1656523595.jpg\" alt=\"中国人力资源职业技能测评中心\">\t\t\t\t</a>\t\t\t</div>\t\t\t<div class=\"search\">\t\t\t\t<div class=\"form\">\t\t\t\t\t<form name=\"frmInfoSearch\" method=\"post\" action=\"/channel/search/l/cn\">\t\t\t\t\t\t<div class=\"dl\">\t\t\t\t\t\t\t<input class=\"button\" name=\"submit8\" type=\"submit\" value=\"搜索\" />\t\t\t\t\t\t\t<div class=\"input\">\t\t\t\t\t\t\t\t<input type=\"text\" name=\"Keywords\" placeholder=\"请输入关键词\">\t\t\t\t\t\t\t</div>\t\t\t\t\t\t</div>\t\t\t\t\t<input type=\"hidden\" name=\"__hash__\" value=\"4f712003d4627940a5b4422c8a7ad3ff_42bb577f199b960e65b078ad827f6c6a\" /></form>\t\t\t\t</div>\t\t\t</div>\t\t</div>\t</div>\t<div class=\"wnav\">\t\t<div class=\"html\">\t\t\t<div class=\"nav\">\t\t\t\t<!-- <div class=\"li selected\"><a href=\"#\">网站首页</a></div> -->\t\t\t\t\t\t\t\t\t\t\t<div class=\"li\">\t\t\t\t\t<a href=\"/\">首页</a>\t\t\t</div>\t\t\t\t\t\t\t<div class=\"li\">\t\t\t\t\t<a href=\"/info.html\">信息公开</a>\t\t\t</div>\t\t\t\t\t\t\t<div class=\"li\">\t\t\t\t\t<a href=\"/jgjs.html\">机构介绍</a>\t\t\t</div>\t\t\t\t\t\t\t<div class=\"li\">\t\t\t\t\t<a href=\"/zhzx.html\">综合资讯</a>\t\t\t</div>\t\t\t\t\t\t\t<div class=\"li\">\t\t\t\t\t<a href=\"/tzgg.html\">通知公告</a>\t\t\t</div>\t\t\t\t\t\t\t<div class=\"li\">\t\t\t\t\t<a href=\"/zcfg.html\">政策法规</a>\t\t\t</div>\t\t\t\t\t\t\t<div class=\"li\">\t\t\t\t\t<a href=\"/jdxw.html\">焦点新闻</a>\t\t\t</div>\t\t\t\t\t\t\t<div class=\"li\">\t\t\t\t\t<a href=\"/rcxm.html\">人才项目</a>\t\t\t</div>\t\t\t\t\t\t\t<div class=\"li\">\t\t\t\t\t<a href=\"/kszx.html\">考试中心</a>\t\t\t</div><div class=\"li selected\">\t\t\t\t\t\t\t\t\t\t\t\t<a href=\"/zscx.html\">证书查询</a>\t\t\t</div>\t\t\t\t\t\t\t<div class=\"li\">\t\t\t\t\t<a href=\"/lxwm.html\">联系我们</a>\t\t\t</div>\t\t</div>\t</div>\t</div>";
//        String replaceInfo2 ="<div class=\"foot\">\t\t\t<div class=\"fnav\">\t\t\t\t<div class=\"li\">版权所有：中国人力资源职业技能测评中心 </div>\t\t\t\t<div class=\"li\">电话：010-83480000</div>\t\t\t\t<div class=\"li\"> 网址：https://www.hrjnjd.org.cn</div>\t\t\t\t<div class=\"li\">地址：</div>\t\t\t</div>\t\t\t\t</div>\t</div></div><div class=\"wfooter\">\t<div style=\"line-height: 50px;\"> <a href=\"#\"> 返回首页 </a> | <a href=\"#\" class=\"favorites\"> 加入收藏 </a> | <a href=\"#\"> 网站地图 </a></div>\t<div id=\"myfooter\">\t \t\t<ul> 特别感谢：<a href=\"//www.xiumiyun.com\" target=\"_blank\">香港服务器</a></ul>\t</div></div><script type=\"text/javascript\" charset=\"utf-8\" src=\"/App/Tpl/Home/Default/Public/static/js/buttonlite.js\"></script><script type=\"text/javascript\" charset=\"utf-8\" src=\"/App/Tpl/Home/Default/Public/static/js/bsharec0.js\"></script>";
//        String replaceInfo3 = "<link rel=\"stylesheet\" href=\"/App/Tpl/Home/Default/Public/static/css/zhengshushow.css\">        <title>证书查询</title>        <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /><meta name=\"author\" content=\"中国人力资源职业技能测评中心\"><meta name=\"keywords\" content=\"中国人力资源职业技能测评中心\"><meta name=\"description\" content=\"202412271659\"><link href=\"/Upload/public/lco.png\" type=\"image/x-icon\" rel=\"icon\"><link href=\"/Upload/public/lco.png\" type=\"image/x-icon\" rel=\"shortcut icon\"><meta name=\"viewport\" content=\"width=1200,inital-scale=10,user-scalable=yes;\" /><script type=\"text/javascript\" src=\"/App/Tpl/Home/Default/Public/static/js/jquery-1.11.3.min.js\"></script><link href=\"/App/Tpl/Home/Default/Public/static/css/css.css\" rel=\"stylesheet\" type=\"text/css\"><script type=\"text/javascript\" src=\"/App/Tpl/Home/Default/Public/static/js/jquery.pd.confirm.js\"></script><link href=\"/App/Tpl/Home/Default/Public/static/css/jquery.pd.confirm.css\" rel=\"stylesheet\" type=\"text/css\"><link href=\"/App/Tpl/Home/Default/Public/static/css/my.css\" rel=\"stylesheet\" type=\"text/css\">";
        String replaceInfo4 = "src=\"/Upload/";
        return finalResult.replace(replaceInfo4,"src=\"http://www.hrjnjd.com/Upload/");
    }


    public static void main(String[] args) {
        try {
            // 调用查询证书的方法
            String name = "张政";
            String certificateNumber = "202412311764";
            String idCardNumber = "342422199611220370";
            String captcha = "6374";  // 假设验证码为 5016
            String cookie = "rpbjb9qhq3q3th44cgsaln0t1n";  // PHPSESSID
            // 第一步：查询证书
            String queryResult = queryCertificate(name, certificateNumber, idCardNumber, captcha, cookie);

            System.out.println(queryResult);
            // 第二步：提取 Data 字段
            String data = extractDataFromJson(queryResult);
            System.out.println(data);
            if (data != null) {
                // 第三步：根据 Data 进行进一步请求
                String finalResult = formatContent(data,cookie);
//                String replaceInfo1 = "<div class=\"html\">\t\t<div class=\"top\">\t\t\t<div class=\"logo\">\t\t\t\t<a href=\"/\">\t\t\t\t\t<img src=\"/Upload/1656523595.jpg\" alt=\"中国人力资源职业技能测评中心\">\t\t\t\t</a>\t\t\t</div>\t\t\t<div class=\"search\">\t\t\t\t<div class=\"form\">\t\t\t\t\t<form name=\"frmInfoSearch\" method=\"post\" action=\"/channel/search/l/cn\">\t\t\t\t\t\t<div class=\"dl\">\t\t\t\t\t\t\t<input class=\"button\" name=\"submit8\" type=\"submit\" value=\"搜索\" />\t\t\t\t\t\t\t<div class=\"input\">\t\t\t\t\t\t\t\t<input type=\"text\" name=\"Keywords\" placeholder=\"请输入关键词\">\t\t\t\t\t\t\t</div>\t\t\t\t\t\t</div>\t\t\t\t\t<input type=\"hidden\" name=\"__hash__\" value=\"4f712003d4627940a5b4422c8a7ad3ff_42bb577f199b960e65b078ad827f6c6a\" /></form>\t\t\t\t</div>\t\t\t</div>\t\t</div>\t</div>\t<div class=\"wnav\">\t\t<div class=\"html\">\t\t\t<div class=\"nav\">\t\t\t\t<!-- <div class=\"li selected\"><a href=\"#\">网站首页</a></div> -->\t\t\t\t\t\t\t\t\t\t\t<div class=\"li\">\t\t\t\t\t<a href=\"/\">首页</a>\t\t\t</div>\t\t\t\t\t\t\t<div class=\"li\">\t\t\t\t\t<a href=\"/info.html\">信息公开</a>\t\t\t</div>\t\t\t\t\t\t\t<div class=\"li\">\t\t\t\t\t<a href=\"/jgjs.html\">机构介绍</a>\t\t\t</div>\t\t\t\t\t\t\t<div class=\"li\">\t\t\t\t\t<a href=\"/zhzx.html\">综合资讯</a>\t\t\t</div>\t\t\t\t\t\t\t<div class=\"li\">\t\t\t\t\t<a href=\"/tzgg.html\">通知公告</a>\t\t\t</div>\t\t\t\t\t\t\t<div class=\"li\">\t\t\t\t\t<a href=\"/zcfg.html\">政策法规</a>\t\t\t</div>\t\t\t\t\t\t\t<div class=\"li\">\t\t\t\t\t<a href=\"/jdxw.html\">焦点新闻</a>\t\t\t</div>\t\t\t\t\t\t\t<div class=\"li\">\t\t\t\t\t<a href=\"/rcxm.html\">人才项目</a>\t\t\t</div>\t\t\t\t\t\t\t<div class=\"li\">\t\t\t\t\t<a href=\"/kszx.html\">考试中心</a>\t\t\t</div><div class=\"li selected\">\t\t\t\t\t\t\t\t\t\t\t\t<a href=\"/zscx.html\">证书查询</a>\t\t\t</div>\t\t\t\t\t\t\t<div class=\"li\">\t\t\t\t\t<a href=\"/lxwm.html\">联系我们</a>\t\t\t</div>\t\t</div>\t</div>\t</div>";
//                String replaceInfo2 ="<div class=\"foot\">\t\t\t<div class=\"fnav\">\t\t\t\t<div class=\"li\">版权所有：中国人力资源职业技能测评中心 </div>\t\t\t\t<div class=\"li\">电话：010-83480000</div>\t\t\t\t<div class=\"li\"> 网址：https://www.hrjnjd.org.cn</div>\t\t\t\t<div class=\"li\">地址：</div>\t\t\t</div>\t\t\t\t</div>\t</div></div><div class=\"wfooter\">\t<div style=\"line-height: 50px;\"> <a href=\"#\"> 返回首页 </a> | <a href=\"#\" class=\"favorites\"> 加入收藏 </a> | <a href=\"#\"> 网站地图 </a></div>\t<div id=\"myfooter\">\t \t\t<ul> 特别感谢：<a href=\"//www.xiumiyun.com\" target=\"_blank\">香港服务器</a></ul>\t</div></div><script type=\"text/javascript\" charset=\"utf-8\" src=\"/App/Tpl/Home/Default/Public/static/js/buttonlite.js\"></script><script type=\"text/javascript\" charset=\"utf-8\" src=\"/App/Tpl/Home/Default/Public/static/js/bsharec0.js\"></script>";
//                String replaceInfo3 = "<link rel=\"stylesheet\" href=\"/App/Tpl/Home/Default/Public/static/css/zhengshushow.css\">        <title>证书查询</title>        <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /><meta name=\"author\" content=\"中国人力资源职业技能测评中心\"><meta name=\"keywords\" content=\"中国人力资源职业技能测评中心\"><meta name=\"description\" content=\"202412271659\"><link href=\"/Upload/public/lco.png\" type=\"image/x-icon\" rel=\"icon\"><link href=\"/Upload/public/lco.png\" type=\"image/x-icon\" rel=\"shortcut icon\"><meta name=\"viewport\" content=\"width=1200,inital-scale=10,user-scalable=yes;\" /><script type=\"text/javascript\" src=\"/App/Tpl/Home/Default/Public/static/js/jquery-1.11.3.min.js\"></script><link href=\"/App/Tpl/Home/Default/Public/static/css/css.css\" rel=\"stylesheet\" type=\"text/css\"><script type=\"text/javascript\" src=\"/App/Tpl/Home/Default/Public/static/js/jquery.pd.confirm.js\"></script><link href=\"/App/Tpl/Home/Default/Public/static/css/jquery.pd.confirm.css\" rel=\"stylesheet\" type=\"text/css\"><link href=\"/App/Tpl/Home/Default/Public/static/css/my.css\" rel=\"stylesheet\" type=\"text/css\">";
//                String replaceInfo4 = "src=\"/Upload/";
//                String replace = finalResult.replace(data, "").replace(data, "").replace(data, "").replace(data,"src=\"http://www.hrjnjd.com/Upload/");
                System.out.println("证书详情: " + finalResult);
                // 调用静态方法提取信息
                String name1 = extractValue(finalResult, "<li>姓 &nbsp;&nbsp;名: (.*?)</li>");
                String idCard = extractValue(finalResult, "<li>身份证号: (.*?)</li>");
                String major = extractValue(finalResult, "<li>专业名称: (.*?)</li>");
                String level = extractValue(finalResult, "<li>技能等级: (.*?)</li>");
                String certificateNo = extractValue(finalResult, "<li>证书编号: (.*?)</li>");
                String issueDate = extractValue(finalResult, "<li>发证时间: (.*?)</li>");
                String imgSrc = extractValue(finalResult, "<ul id=\"my1\">                <img src=\"(.*?)\"");

                // 打印提取结果
                System.out.println("姓名: " + name1);
                System.out.println("身份证号: " + idCard);
                System.out.println("专业名称: " + major);
                System.out.println("技能等级: " + level);
                System.out.println("证书编号: " + certificateNo);
                System.out.println("发证时间: " + issueDate);
                System.out.println("图片地址: " + imgSrc);
            } else {
                System.out.println("未找到 Data 字段，无法继续请求");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
